package com.ekuaitu.kuaitu.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.base.BaseActivity;
import com.ekuaitu.kuaitu.bean.AccountBean;
import com.ekuaitu.kuaitu.bean.AlipayPreBean;
import com.ekuaitu.kuaitu.bean.ChargeResultEvent;
import com.ekuaitu.kuaitu.bean.DepositCarResultEvent;
import com.ekuaitu.kuaitu.bean.RechargeAdBean;
import com.ekuaitu.kuaitu.bean.WXPreBean;
import com.ekuaitu.kuaitu.payment.AlipayUtils;
import com.ekuaitu.kuaitu.payment.WXPayUtils;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.utils.ToastUtils;
import com.ekuaitu.kuaitu.widget.NoScrollGridView;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.StatusBarUtil;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jieyaozu on 2017/3/23.
 * 用户充值页面
 */

public class ChargeMoneyActivity extends BaseActivity implements AMapLocationListener {
    @BindView(R.id.charge_money_options)
    NoScrollGridView mGridView;
    @BindView(R.id.wallet_tv_geren)
    TextView myselfMoney;
    @BindView(R.id.charge_button)
    TextView btCharge;
    @BindView(R.id.weixin_radiobutton)
    RadioButton rbWeixin;
    @BindView(R.id.zfb_radiobutton)
    RadioButton rbZfb;
    @BindView(R.id.charge_money_wx)
    RelativeLayout chargeMoneyWx;
    @BindView(R.id.charge_money_zfb)
    RelativeLayout chargeMoneyZfb;
    @BindView(R.id.charge_money_line)
    View chargeMoneyLine;
    @BindView(R.id.scroll_content)
    ScrollView scrollContent;

    @BindView(R.id.progressBar_my_account)
    RelativeLayout progressBar;
    @BindView(R.id.prompt_message)
    TextView tvPromptMsg;
    private Context mContext = this;
    private GridViewAdapter gridViewAdapter;
    private LatLng curPosition;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private int payMethod = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_charge_money;
    }

    @Override
    public void initData() {
        super.initData();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryWhite), 0, true);
        gridViewAdapter = new GridViewAdapter();
        mGridView.setAdapter(gridViewAdapter);
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        scrollContent.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
        //显示可用的支付方式

        if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            chargeMoneyWx.setVisibility(View.VISIBLE);
            chargeMoneyZfb.setVisibility(View.VISIBLE);
            chargeMoneyLine.setVisibility(View.VISIBLE);
            rbWeixin.setChecked(true);
            rbZfb.setChecked(false);
            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
            chargeMoneyWx.setVisibility(View.VISIBLE);
            chargeMoneyZfb.setVisibility(View.GONE);
            chargeMoneyLine.setVisibility(View.GONE);
            rbWeixin.setChecked(true);
            rbZfb.setChecked(false);
            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            chargeMoneyWx.setVisibility(View.GONE);
            chargeMoneyZfb.setVisibility(View.VISIBLE);
            chargeMoneyLine.setVisibility(View.GONE);
            rbWeixin.setChecked(false);
            rbZfb.setChecked(true);
            payMethod = 2;
        } else {
            chargeMoneyWx.setVisibility(View.GONE);
            chargeMoneyZfb.setVisibility(View.GONE);
            chargeMoneyLine.setVisibility(View.GONE);
            payMethod = 0;
        }


        rbWeixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 1;
                    rbZfb.setChecked(false);
                }
            }
        });


        rbZfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 2;
                    rbWeixin.setChecked(false);
                }
            }
        });

        getMoneyOptionsData();
        getRechargeAd();
    }

    @OnClick({R.id.return_charge, R.id.charge_button})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.return_charge:
                finish();
                break;
            case R.id.charge_button:
                if (payMethod == 1) {
                    getWxpayParams((int) (gridViewAdapter.getSelectPrice() * 100) + "");
                } else if (payMethod == 2) {
                    getAlipayParams((int) (gridViewAdapter.getSelectPrice() * 100) + "");
                }
                break;
        }
    }
/*
    @Override
    protected void onResume() {
        super.onResume();
        if (Constants.isChargeComplete) {
            Constants.isChargeComplete = false;
            getMoneyOptionsData();
        }
    }*/

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Subscribe
    public void onChargeResult(ChargeResultEvent event) {
        if (event.payResult == 0) {
            //支付成功
            scrollContent.smoothScrollTo(0, 0);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    //再次刷新请求信息
                    getMoneyOptionsData();
                }
            }, 3000);
        } else {
            progressBar.setVisibility(View.GONE);
        }

    }


    /**
     * 获取金额数据
     */
    private void getMoneyOptionsData() {
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getMyAccount(MyApplication.getInstance().getRequestFieldMap()).enqueue(new Callback<AccountBean>() {
            @Override
            public void onResponse(Call<AccountBean> call, Response<AccountBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        scrollContent.setVisibility(View.VISIBLE);
                        progressBar.setVisibility(View.GONE);
                        AccountBean.AttachmentBean.AccountModelBean account = response.body().getAttachment().getAccountModel();
                        DecimalFormat df = new DecimalFormat("0.00");
                        myselfMoney.setText(df.format(account.getBalance()));
                        List<AccountBean.AttachmentBean.RechargeModelBean> chargeValue_list = response.body().getAttachment().getRechargeModel();
                        chargeValue_list.get(0).setChecked(true);
                        if (chargeValue_list != null && chargeValue_list.size() != 0) {
                            gridViewAdapter.replaceAll(chargeValue_list);
                        }
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(ChargeMoneyActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(ChargeMoneyActivity.this, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AccountBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(ChargeMoneyActivity.this, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 判断是否有活动
     */
    private void getRechargeAd() {
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getRechargeAd(MyApplication.getInstance().getRequestFieldMap())
                .enqueue(new Callback<RechargeAdBean>() {
                    @Override
                    public void onResponse(Call<RechargeAdBean> call, Response<RechargeAdBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                RechargeAdBean rechargeAdBean = response.body();
                                List<RechargeAdBean.Attachment.Ad> adList = rechargeAdBean.getAttachment().getAdList();
                                if (adList == null || adList.size() == 0) {
                                    tvPromptMsg.setVisibility(View.GONE);
                                } else {
                                    String content = adList.get(0).getContent();
                                    if (!TextUtils.isEmpty(content)) {
                                        tvPromptMsg.setVisibility(View.VISIBLE);
                                        tvPromptMsg.setText(content);
                                    } else {
                                        tvPromptMsg.setVisibility(View.GONE);
                                    }
                                }
                            } else {
                                tvPromptMsg.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<RechargeAdBean> call, Throwable t) {

                    }
                });
    }

    /**
     * 微信充值
     *
     * @param chargeValue
     */
    private void getWxpayParams(String chargeValue) {
        String longitude;
        String latitude;
        if (curPosition == null) {
            longitude = "";
            latitude = "";
        } else {
            longitude = curPosition.longitude + "";
            latitude = curPosition.latitude + "";
        }
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatRecharge(MyApplication.getInstance().getRequestFieldMap(), chargeValue, "2", longitude, latitude).enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(ChargeMoneyActivity.this).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 2);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(ChargeMoneyActivity.this);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(ChargeMoneyActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(ChargeMoneyActivity.this, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(ChargeMoneyActivity.this, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 支付宝充值
     *
     * @param chargeValue
     */
    private void getAlipayParams(String chargeValue) {
        String longitude;
        String latitude;
        if (curPosition == null) {
            longitude = "";
            latitude = "";
        } else {
            longitude = curPosition.longitude + "";
            latitude = curPosition.latitude + "";
        }
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayRecharge(MyApplication.getInstance().getRequestFieldMap(), chargeValue, "1", longitude, latitude)
                .enqueue(new Callback<AlipayPreBean>() {
                    @Override
                    public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 2);
                                String orderInfo = response.body().getAttachment().getStr();
                                AlipayUtils alipayUtils = new AlipayUtils(ChargeMoneyActivity.this);
                                alipayUtils.aliPay(orderInfo);
                            } else {
                                progressBar.setVisibility(View.GONE);
                                ToastCompat.makeText(ChargeMoneyActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                            }
                        } else {
                            progressBar.setVisibility(View.GONE);
                            ToastCompat.makeText(ChargeMoneyActivity.this, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(ChargeMoneyActivity.this, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        } else {
            mLocationClient.startLocation();
        }
    }

    public class GridViewAdapter extends BaseAdapter {
        private int selectPos = 0;
        private List<AccountBean.AttachmentBean.RechargeModelBean> chargeValue_list = new ArrayList<>();

        public void replaceAll(List<AccountBean.AttachmentBean.RechargeModelBean> rechargeModelBeanList) {
            if (rechargeModelBeanList != null) {
                chargeValue_list.clear();
                chargeValue_list.addAll(rechargeModelBeanList);
            }

            for (int i = 0; i < chargeValue_list.size(); i++) {
                AccountBean.AttachmentBean.RechargeModelBean modelBean = chargeValue_list.get(i);
                if (modelBean.getRechargePrice() == 50) {
                    selectPos = i;
                }

            }
            notifyDataSetChanged();
        }

        public double getSelectPrice() {
            return chargeValue_list.get(selectPos).getRechargePrice();
        }

        @Override
        public int getCount() {
            return chargeValue_list.size();
        }

        @Override
        public Object getItem(int position) {
            return chargeValue_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = View.inflate(ChargeMoneyActivity.this, R.layout.item_gridview_chargemoney, null);
            RelativeLayout background = (RelativeLayout) view.findViewById(R.id.layout_bg);
            AccountBean.AttachmentBean.RechargeModelBean modelBean = chargeValue_list.get(position);

            if (selectPos == position) {
                background.setBackgroundResource(R.drawable.shape_green_corner);
            } else {
                background.setBackgroundResource(R.drawable.corner_gray_shape);
            }

            TextView tvChargeMoney = (TextView) view.findViewById(R.id.charge_money);
            TextView tvGiveMoney = (TextView) view.findViewById(R.id.give_money);
            TextView tvXianshi = (TextView) view.findViewById(R.id.xianshi_icon);

            tvChargeMoney.setText("充￥" + modelBean.getRechargePrice());
            if (modelBean.getExtraPrice() != 0) {
                tvGiveMoney.setVisibility(View.VISIBLE);
                tvXianshi.setVisibility(View.VISIBLE);
                tvGiveMoney.setText("送￥" + modelBean.getExtraPrice());
            } else {
                tvGiveMoney.setVisibility(View.GONE);
                tvXianshi.setVisibility(View.GONE);
            }

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectPos = position;
                    notifyDataSetChanged();
                }
            });
            return view;
        }
    }
}
